import sortedcontainers
class Solution(object):
    def closestRoom(self, rooms, queries):
        n = len(rooms)
        m = len(queries)
        queries = [[min_size, prefer_id, index] for index, (prefer_id, min_size) in enumerate(queries)]
        queries.sort(reverse=True)
        rooms.sort(key = lambda x: x[1], reverse=True)
        ans = [0] * m
        index_r = 0
        wait = sortedcontainers.SortedList()
        for min_size, prefer_id, ans_index in queries:
            while index_r < n and rooms[index_r][1] >= min_size:
                wait.add(rooms[index_r][0])
                index_r += 1
            if wait:
                min_dist= float('inf')
                min_id = -1
                t = wait.bisect_right(prefer_id)
                if t > 0:
                    min_dist = abs(prefer_id - wait[t - 1])
                    min_id = wait[t - 1]
                if t < len(wait):
                    if abs(prefer_id - wait[t]) < min_dist:
                        min_id = wait[t]
                ans[ans_index] = min_id
            else:
                ans[ans_index] = -1
        return ans




data = Solution()
rooms = [[2,2],[1,2],[3,2]]
queries = [[3,1],[3,3],[5,2]]
print(data.closestRoom(rooms, queries))